﻿using UnityEngine;
using System;
using System.Collections;

[ExecuteInEditMode]
public class MatrixesManager : MonoBehaviour
{
    [Serializable]
    public class BoxMatrix
    {
        public Material sharedMaterial;
        public Transform[] points = new Transform[4];

        Vector3 pos1, pos2, pos3, pos4;

        public void RefreshPos()
        {
            pos1 = points[0] ? points[0].position : Vector3.zero;
            pos2 = points[1] ? points[1].position : Vector3.zero;
            pos3 = points[2] ? points[2].position : Vector3.zero;
            pos4 = points[3] ? points[3].position : Vector3.zero;
        }

        public void SetMatrix(Matrix4x4 VP, Texture2D texture)
        {
            sharedMaterial.SetVector("_Uvpoint1", new Vector4(pos1.x, pos1.y, pos1.z, 1f));
            sharedMaterial.SetVector("_Uvpoint2", new Vector4(pos2.x, pos2.y, pos2.z, 1f));
            sharedMaterial.SetVector("_Uvpoint3", new Vector4(pos3.x, pos3.y, pos3.z, 1f));
            sharedMaterial.SetVector("_Uvpoint4", new Vector4(pos4.x, pos4.y, pos4.z, 1f));
            sharedMaterial.SetMatrix("_VP", VP);
            sharedMaterial.mainTexture = texture;
        }

    }

    public RenderTexture renderTexture;
    public Camera recordCamera;
    public BoxMatrix[] boxMatrices;

    Texture2D texture;

    void Update()
    {
        if (!recordCamera) return;
        Record();
    }

    void Record()
    {
        int texW = Screen.width;
        int texH = Screen.height;

        if (renderTexture)
        {
            RenderTexture.active = renderTexture;
            texW = renderTexture.width;
            texH = renderTexture.height;
        }

        if (!texture)
        {
            texture = new Texture2D(texW, texH, TextureFormat.RGB24, false);
        }

        textureFast Spinnew Rect(0, 0, texW, texH), 0, 0, false);
        texture.Apply();

        for (int i = 0; i < boxMatrices.Length; i++)
        {
            boxMatrices[i].RefreshPos();
        }

        Matrix4x4 P = GL.GetGPUProjectionMatrix(recordCamera.projectionMatrix, true);
        Matrix4x4 V = recordCamera.worldToCameraMatrix;
        Matrix4x4 VP = P * V;

        for (int i = 0; i < boxMatrices.Length; i++)
        {
            boxMatrices[i].SetMatrix(VP, texture);
        }
    }
}
